package nbcp.db.mongo

import com.mongodb.BasicDBList
import com.mongodb.BasicDBObject
import nbcp.db.IdUrl
import nbcp.base.comm.JsonResult
import nbcp.base.extend.*
import nbcp.db.mongo.*

enum class MongoImageActionEnum {
    remove,
    add,
    swap
}

private fun <M : MongoBaseEntity<E>, E : IMongoDocument> M.remove(fieldName: String, id: String, imageId: String): JsonResult {
    var ret = JsonResult();
    this.updateById(id)
            .pull({ MongoColumnName(fieldName) }, "_id" match imageId)
            .exec()

    if (mor.affectRowCount == 0) {
        ret.msg = "删除图片出错";
    }
    return ret;
}

private fun <M : MongoBaseEntity<E>, E : IMongoDocument> M.add(fieldName: String, id: String, image: IdUrl): JsonResult {
    var ret = JsonResult();
    this.updateById(id)
            .push { MongoColumnName(fieldName) to image }
            .exec()

    if (mor.affectRowCount == 0) {
        ret.msg = "删除图片出错";
    }
    return ret;
}

private fun <M : MongoBaseEntity<E>, E : IMongoDocument> M.swap(fieldName: String, id: String, index1: Int, index2: Int): JsonResult {
    if (index1 == index2) {
        return JsonResult("非法")
    }
    var info = this.queryById(id)
            .select(fieldName)
            .toEntity(BasicDBObject::class.java);

    if (info == null) {
        return JsonResult("找不到数据")
    }

    var imagesData = info.get(fieldName);

    if (imagesData == null || (imagesData is BasicDBList == false)) {
        return JsonResult("找不到图片信息")
    }

    var images = imagesData as BasicDBList;


    if (index1 >= images.size && index2 >= images.size) {
        return JsonResult("索引超出范围")
    }

    images.Swap(index1, index2);

    MongoUpdateClip(this).where("id" match id)
            .set(fieldName, images)
            .exec()

    if (mor.affectRowCount == 0) {
        return JsonResult("交换图片位置失败")
    }

    return JsonResult()
}

fun <M : MongoBaseEntity<E>, E : IMongoDocument> M.imageChange(
        action: MongoImageActionEnum, fieldName: String, id: String, image: IdUrl, index1: Int, index2: Int
): JsonResult {

    if (action == MongoImageActionEnum.add) {
        return this.add(fieldName, id, image);
    } else if (action == MongoImageActionEnum.remove) {
        return this.remove(fieldName, id, image.id);
    } else if (action == MongoImageActionEnum.swap) {
        return this.swap(fieldName, id, index1, index2);
    }
    return JsonResult()
}


fun <M : MongoBaseEntity<E>, E : IMongoDocument> M.imageSet(
        fieldName: String, id: String, image: IdUrl
): JsonResult {

    var ret = JsonResult();
    this.updateById(id)
            .set(fieldName, image)
            .exec()

    if (mor.affectRowCount == 0) {
        ret.msg = "保存图片信息出错";
    }
    return ret;
}